define(['comps/ajax', 'text!tpl/comps/record.tpl', 'art', 'jweixin', 'underscore', 'css!/assets/css/comps/record.css'],
    function (ajax, tpl, art, wx, _) {
        const delegateEventSplitter = /^(\S+)\s*(.*)$/
        const localStorage = window.localStorage
        let voice = {}
        let defaultConfig = {}
        function preloadImage(arr) {
            var newimages = [], loadedimages = 0
            for (var i = 0; i < arr.length; i++) {
                newimages[i] = new Image()
                newimages[i].src = arr[i]
                loadedimages++
            }
        }

        preloadImage(['assets/img/pause.svg', 'assets/img/recording.gif'])

        function Record(config) {
            this._config = _.extend({}, defaultConfig, config)
            this.id = _.uniqueId('record')
            this.events = {
                'touchstart a[operate="record"]': 'startRecord',
                'touchend a[operate="record"]': 'endRecord',
                'click a[operate="play"]': 'playRecord',
                'click a[operate="confirm"]': 'confirm',
                'click a[operate="cancel"]': 'cancel'
            }

            this.initialize.call(this, config.el)
        }

        _.extend(Record.prototype,Backbone.Events)

        Record.prototype.initialize = function ($el) {
            const _this = this
            localStorage.removeItem('allowRecord')
            if (!$('#recordingToast_' + this.id).length) {
                $(art.compile(tpl)({id: this.id})).appendTo($('body'))
            }
            this.$el = $('#recordingToast_' + this.id)
            this.delegateEvents()
            $el.on('click', function () {
                if (localStorage.allowRecord) {
                    $('#recordingToast_' + _this.id).show()
                } else {
                    $.alert('用户已拒绝授权录音')
                }
            })
            if (!localStorage.allowRecord) {
                wx.startRecord({
                    success: function () {
                        localStorage.allowRecord = 1
                        wx.stopRecord()
                    },
                    fail:function(){
                      console.log('开始录音失败')
                    },
                    cancel: function () {
                        $.alert('你已经拒绝授权录音')
                    }
                })
            }
        }

        Record.prototype.delegateEvents = function () {
            this.undelegateEvents();
            var events = _.result(this, 'events')
            for (var key in events) {
                var method = events[key];
                if (!_.isFunction(method)) method = this[method];
                if (!method) continue;
                var match = key.match(delegateEventSplitter);
                this.delegate(match[1], match[2], _.bind(method, this));
            }
            return this;
        }

        Record.prototype.delegate = function (eventName, selector, listener) {
            $('#recordingToast_' + this.id).on(eventName + '.delegateEvents' + this.id, selector, listener);
            return this
        }

        Record.prototype.undelegateEvents = function () {
            if ($('#recordingToast_' + this.id)) $('#recordingToast_' + this.id).off('.delegateEvents' + this.id);
            return this;
        }

        Record.prototype.startRecord = function (event) {
            event.preventDefault();
            const _this = this
            var startTime = this.startTime = new Date().getTime();
            $(event.currentTarget).addClass('startRecording');
            if (!localStorage.allowRecord) {
                $.alert('用户拒绝授权录音')
            }
            this.recordTimer = setTimeout(function () {
                wx.startRecord({
                    success: function () {
                        $('#play_' + _this.id).removeClass('playing').css('opacity', 0)
                    }
                })
            }, 500)
            wx.onVoiceRecordEnd({
                complete: function (res) {
                    voice.localId = res.localId;
                    $('#play_' + _this.id).css('opacity', 1)
                    $('#confirm_' + _this.id).show()
                    $.alert('录音时间已超过一分钟')
                }
            })
        }

        Record.prototype.endRecord = function (event) {
            event.preventDefault();
            const _this = this
            var endTime = new Date().getTime();
            if ((endTime - this.startTime) < 500) {
                endTime = 0;
                this.startTime = 0;
                clearTimeout(this.recordTimer)
                $(event.currentTarget).removeClass('startRecording');
                return
            }
            $(event.currentTarget).removeClass('startRecording');
            wx.stopRecord({
                success: function (res) {
                    voice.localId = res.localId;
                    $('#play_' + _this.id).css('opacity', 1)
                    $('#confirm_' + _this.id).show()
                },
                fail: function (res) {
                    $.alert(JSON.stringify(res));
                }
            })
        }

        Record.prototype.playRecord = function () {
            const _this = this
            $('#play_' + this.id).toggleClass('playing')
            if (voice.localId == '') {
                $.alert('请先使用 startRecord 接口录制一段声音');
                return;
            }
            wx.playVoice({
                localId: voice.localId
            })
            wx.onVoicePlayEnd({
                success: function (res) {
                    $('#play_' + _this.id).removeClass('playing')
                }
            })

        }

        Record.prototype.confirm = function () {
            const _this = this
            if (voice.localId == '') {
                $.alert('请先使用 startRecord 接口录制一段声音');
                return;
            }
            wx.uploadVoice({
                localId: voice.localId,
                success: function (res) {
                    voice.serverId = res.serverId
                    ajax.post('getMediaFile.do',{
                        //media_id:'RK9vcUTRoquHuJfENmgssAwKh7yWIH53vmYa2-x2HyNN31kAkC7nQ72XSzRLdRgY',
                        media_id:res.serverId,
                        relation_field:19
                    }).success(function(resp){
                        if(!resp){
                            $.toast('操作失败', 1000)
                        }else{
                            $.toast('提交成功', 1000)
                            _this.trigger('upload:success',resp)
                            _this.hide()
                        }
                    })
                }
            })
        }

        Record.prototype.cancel = function (event) {
            event.preventDefault()
            this.hide()
        }

        Record.prototype.hide = function () {
            $('#recordingToast_' + this.id).hide()
            $('#play_' + this.id).removeClass('playing').css('opacity', 0)
            $('#confirm_' + this.id).hide()

        }

        return {
            init: function ($el) {
                return new Record($el)
            }
        }
})